//
//  FunInfoViewController.m
//  心水宝典
//
//  Created by zr on 2018/8/31.
//  Copyright © 2018年 zr. All rights reserved.
//

#import "FunInfoViewController.h"
#import "FunInfoModel.h"
#import "FunInfoTableViewCell.h"

@interface FunInfoViewController ()<UIWebViewDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic, weak)UILabel * titleLabel;
@property (nonatomic, weak)UIWebView * webView;
@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)NSMutableArray <FunInfoModel *> * modelArray;
@property (nonatomic, weak)UITextField * sayTextFiled;

@end

@implementation FunInfoViewController


- (void)viewWillAppear:(BOOL)animated{
    
    NSString * url = [NSString stringWithFormat:@"/api/article/%@",self.ID];
    
    [[NetworkTool sharedTools] GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        int code = [responseObject[@"code"] intValue];
        
        if (code == 200) {
            
            NSDictionary * dict = responseObject[@"data"];
            
            self.titleLabel.text = dict[@"title"];
            NSURL * urlPath = [NSURL fileURLWithPath:[NSBundle mainBundle].bundlePath];
            [self.webView loadHTMLString:dict[@"content"] baseURL:urlPath];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = WHITE_COLOR;
    self.modelArray = [NSMutableArray array];
    
    [self setupNav];
    [self setupUI];
    [self loadData];
}


- (void)loadData{
    
    [self.modelArray removeAllObjects];
    
    NSString * url = [NSString stringWithFormat:@"/api/comment?project_id=1&type=1&item_id=%@",self.ID];
    
    [[NetworkTool sharedTools] GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *array = [NSArray yy_modelArrayWithClass:[FunInfoModel class] json:responseObject[@"data"]];
        
        [self.modelArray addObjectsFromArray:array];
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}


- (void)setupNav{
    
    self.title = @"趣味测算";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    //    backButton.frame = CGRectMake(0, 0, 20 * SCREENH6, 20 * SCREENH6);
    backButton.size = CGSizeMake(20 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}


- (void)setupUI{
    
    UILabel * titleLabel = [UILabel new];
    
    titleLabel.textColor = BLACK_COLOR;
    titleLabel.font = [UIFont systemFontOfSize:20 * SCREENH6];
    
    self.titleLabel = titleLabel;
    
    [self.view addSubview:self.titleLabel];
    
    
    UIWebView *webView = [[UIWebView alloc] init];
    webView.scalesPageToFit = YES;
        webView.delegate = self;
    webView.backgroundColor = WHITE_COLOR;
    
    self.webView = webView;
    
    [self.view addSubview:self.webView];
    
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 230 * SCREENH6, SCREEN_WIDTH, SCREENH_HEIGHT - 350 * SCREENH6) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.rowHeight = 120 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[FunInfoTableViewCell class] forCellReuseIdentifier:@"FunInfoTableViewCell"];
    
    [self.view addSubview:self.tableView];
    
    
    UITextField * sayTextFiled = [[UITextField alloc] init];
    
    sayTextFiled.borderStyle = UITextBorderStyleRoundedRect;
    sayTextFiled.backgroundColor = [UIColor whiteColor];
    //设置光标颜色
    sayTextFiled.tintColor = [UIColor blackColor];
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = [UIColor grayColor];
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    sayTextFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"写点什么" attributes:attrs];
    sayTextFiled.textColor = [UIColor blackColor];
    sayTextFiled.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22 * SCREENH6, 0)];
    //设置显示模式为永远显示(默认不显示)
    sayTextFiled.leftViewMode = UITextFieldViewModeAlways;
    sayTextFiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    UIView * rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 35 * SCREENH6, 20 * SCREENH6)];
    UIImageView *image=[[UIImageView alloc] initWithFrame:CGRectMake(5, 0, 15 * SCREENH6, 20 * SCREENH6)];//WithImage:[UIImage imageNamed:@"手机号"]];
    image.image = ImageNamed(@"xie1");
    [rightView addSubview:image];
    sayTextFiled.leftView = rightView;
    sayTextFiled.leftViewMode = UITextFieldViewModeAlways;
    sayTextFiled.returnKeyType = UIReturnKeyDone;
    sayTextFiled.delegate = self;
    
    self.sayTextFiled = sayTextFiled;
    
    [self.view addSubview:self.sayTextFiled];
}


- (void)viewDidLayoutSubviews{
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.top.mas_equalTo(self.view).offset(10 * SCREENH6);
    }];
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.titleLabel);
        make.trailing.mas_equalTo(self.view).offset(-15 * SCREENH6);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(10 * SCREENH6);
        make.height.mas_equalTo(200 * SCREENH6);
    }];
    
    [self.sayTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).offset(-10 * SCREENH6);
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(-15 * SCREENH6);
        make.height.mas_equalTo(35 * SCREENH6);
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.modelArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FunInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FunInfoTableViewCell" forIndexPath:indexPath];
    
    cell.model = self.modelArray[indexPath.row];
    cell.subLabel.text = [NSString stringWithFormat:@"%lu楼",indexPath.row];
    
    return cell;

}


- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '200%'"];
}

//实现UITextField代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    SHOWHUD;
    
    [textField resignFirstResponder];//取消第一响应者
    NSString * token = DEF_GET_OBJECT(@"token");
    NSDictionary * dict = @{@"content":textField.text,@"item_id":self.ID,@"type":@"1",@"project_id":@"1",@"token":token};
    
    [[NetworkTool sharedTools] POST:@"/api/comment" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        HIDDENHUD;
        
        int code = [responseObject[@"code"] intValue];
        
        if (code == 200) {
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"恭喜你评论成功"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      self.sayTextFiled.text = @"";
                                                                      [self loadData];
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseObject[@"msg"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        HIDDENHUD;
    }];
    
    return YES;
}

- (void)backToView {
    
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
